//
//  WiringChooseViewController.m
//  GKBHouse
//
//  Created by hcy on 14-1-15.
//
//

#import "WiringChooseViewController.h"
#import "GKBNavigationBar.h"

@interface WiringChooseViewController ()

@property (retain, nonatomic)NSArray *equipmentArray;

@property (retain, nonatomic)NSMutableDictionary *timingDic;
@property (assign, nonatomic) id target;
@property (assign, nonatomic) SEL changeAction;

@end

@implementation WiringChooseViewController

- (void)dealloc
{
    self.equipmentArray = nil;
    self.timingDic = nil;
    
    self.gridView = nil;
    self.selectedIndexSet = nil;
    
    [super dealloc];
}

- (id)initWithTimingDic:(NSMutableDictionary *)dic saveTarget:(id)target action:(SEL)action
{
    self = [super initWithNibName:@"WiringChooseViewController" bundle:nil];
    if (self) {
        // Custom initialization
        self.timingDic = dic;
        self.target = target;
        self.changeAction = action;
    }
    return self;
    
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];
    
    [self initTopBar];
    [self initData];
    [self initView];
    
    self.selectedIndexSet = [NSMutableIndexSet indexSet];
    
    NSString *switchStr = [self.timingDic objectForKey:@"switchStr"];
    NSArray *switchArray = [switchStr componentsSeparatedByString:@","];
    
    for (NSString *switchId in switchArray) {
        if ([switchId length]>0) {
            [self.selectedIndexSet addIndex:switchId.integerValue];
        }
    }
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
//{
//    // Return YES for supported orientations
//    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
//}


#pragma mark - init

- (void)initTopBar
{
    GKBNavigationBar *topBar = [[GKBNavigationBar alloc]init];
//    [topBar setTarget:self returnAction:@selector(dismissView) withTitle:NSLocalizedString(@"timingSet", nil)];
    topBar.refreshButton.hidden = YES;
    topBar.returnButton.hidden = YES;
    
    [topBar.titleLabel setText:NSLocalizedString(@"timingSet", nil)];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setFrame:[GKBNavigationBar rightBtn2Rect1]];
    [backBtn setImage:[UIImage imageNamed:@"backBut.png"] forState:UIControlStateNormal];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"buttonBlue.png"] forState:UIControlStateNormal];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"buttonBlueSelected.png"] forState:UIControlStateHighlighted];
    [backBtn addTarget:self action:@selector(dismissView) forControlEvents:UIControlEventTouchUpInside];
    [topBar addSubview:backBtn];
    
    UIButton *okBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [okBtn setFrame:[GKBNavigationBar rightBtnRect1]];
    [okBtn setBackgroundImage:[UIImage imageNamed:@"buttonBlue.png"] forState:UIControlStateNormal];
    [okBtn setBackgroundImage:[UIImage imageNamed:@"buttonBlueSelected.png"] forState:UIControlStateHighlighted];
    [okBtn setTitle:NSLocalizedString(@"ok", nil) forState:UIControlStateNormal];
    [okBtn addTarget:self action:@selector(okAction) forControlEvents:UIControlEventTouchUpInside];
    [topBar addSubview:okBtn];
    
    [self.view addSubview:topBar];
    [topBar release];
    
}

- (void)dismissView
{
    [self dismissModalViewControllerAnimated:NO];
}

- (void)initView
{
    CGFloat tableW = DEVICE_HEIGHT - 10.0f;
    CGFloat tableH = DEVICE_WIDTH - kTopBarHeight - 10.0f;
    CGFloat tableX = 5.0f;
    CGFloat tableY = kTopBarHeight + 5.0f;
    
//    UIScrollView *wiringsView = [[UIScrollView alloc]initWithFrame:CGRectMake(tableX, tableY, tableW, tableH)];
//    [wiringsView setBackgroundColor:[UIColor whiteColor]];
//    [wiringsView.layer setCornerRadius:11];
//    [self.view addSubview:wiringsView];
//    [wiringsView release];
    
    // grid view sits on top of the background image
    self.gridView = [[[AQGridView alloc] initWithFrame:CGRectMake(tableX, tableY, tableW, tableH)] autorelease];
//    self.gridView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    self.gridView.backgroundColor = [UIColor whiteColor];
    self.gridView.opaque = NO;
    self.gridView.scrollEnabled = YES;
    self.gridView.dataSource = self;
    self.gridView.delegate = self;
   
    self.gridView.requiresSelection = YES;
    [self.view addSubview:self.gridView];
    
//    [self loadFileList];
    
    [self.gridView reloadData];

}

- (void)initData
{
    GKBMainController *main = [GKBMainController mainCtr];
    
    self.equipmentArray = main.equipments;
}


#pragma mark -
#pragma mark Grid View Data Source

- (NSUInteger) numberOfItemsInGridView: (AQGridView *) aGridView
{
    return [self.equipmentArray count];
}

- (AQGridViewCell *)gridView:(AQGridView *)aGridView cellForItemAtIndex:(NSUInteger)index
{
    static NSString *CellIdentifier = @"WiringGridViewCell";
    
    WiringGridViewCell *cell = (WiringGridViewCell *)[aGridView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[WiringGridViewCell alloc]initWithFrame:CGRectMake(0.0f, 0.0f, aGridView.width/3 - 0.0f, 50.0f - 0.0f) reuseIdentifier:CellIdentifier];
        [cell setSelectionStyle: UITableViewCellSelectionStyleNone];
    }
    
    NSDictionary *dic = [self.equipmentArray objectAtIndex:index];
    NSString *switchId = [dic objectForKey:@"switchId"];
    
    if ([switchId length]>0) {
        if ([self.selectedIndexSet containsIndex:switchId.integerValue]) {
            cell.checkBtn.selected = YES;
        }
        else
        {
            cell.checkBtn.selected = NO;
        }
    }
    else
    {
        cell.checkBtn.selected = NO;
    }
    
    
    NSDictionary *equipment = [self.equipmentArray objectAtIndex:index];
    
    NSString *tagName = [equipment objectForKey:@"tagName"];
    NSString *name = [equipment objectForKey:@"name"];
    NSString *title = [tagName stringByAppendingString:name];
    NSString *type = [equipment objectForKey:@"type"];
    
//    if ([type isEqualToString:@"9"]) {
//        GKBMainController *main = [GKBMainController mainCtr];
//        for (Equipment *euq in main.protectArray) {
//            NSString *switchId = [equipment objectForKey:@"switchId"];
//            if ([switchId isEqualToString:euq.switchId]) {
//                title = [tagName stringByAppendingString:euq.name];
//                title = euq.name;
//            }
//        }
//    }
    
    cell.titleLabel.text = title;
    
    
    return cell;
}

- (CGSize)portraitGridCellSizeForGridView:(AQGridView *)aGridView
{
    return CGSizeMake(aGridView.width/3, 50);
}

- (void)gridView:(AQGridView *)gridView didSelectItemAtIndex:(NSUInteger)index
{
    // 取消选中
    [gridView deselectItemAtIndex:index animated:NO];
    
    NSDictionary *dic = [self.equipmentArray objectAtIndex:index];
    NSString *switchId = [dic objectForKey:@"switchId"];
    
    if ([switchId length]>0) {

        if ([self.selectedIndexSet containsIndex:switchId.integerValue]) {
            [self.selectedIndexSet removeIndex:switchId.integerValue];
        }
        else
        {
            [self.selectedIndexSet addIndex:switchId.integerValue];
        }
        
        [gridView reloadData];

    }
    
    
}


#pragma mark - action

- (void)okAction
{
    NSMutableArray *array = [NSMutableArray array];
    [self.selectedIndexSet enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
        NSString *index = [NSString stringWithFormat:@"%d",idx];
        [array addObject:index];
    }];
    
    NSString *switchStr = [array componentsJoinedByString:@","];
    
    [self.timingDic setObject:switchStr forKey:@"switchStr"];
    
    if (self.target && self.changeAction) {
        [self.target performSelector:self.changeAction];
    }
    [self dismissView];
}


@end
